package org.springblade.modules.app.controller;

import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.boot.file.BladeFile;
import org.springblade.core.launch.props.BladeProperties;
import org.springblade.core.tool.api.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by admin on 2019/4/4.
 */
@Controller
@RequestMapping("/app/upload")
public class UploadController extends BladeController {
	@Autowired
	BladeProperties bladeProperties;
	@Autowired
	private ResourceLoader resourceLoader;

	@ResponseBody
	@PostMapping("/imgs")
	public R uploadImg(@RequestParam("file") MultipartFile file) {
		return this.commonUpload(file);
	}

	@ResponseBody
	@PostMapping("/imgsUeditor")
	public R uploadUeditor(@RequestParam("img") MultipartFile file) {
		return this.commonUpload(file);
	}

	@ResponseBody
	@GetMapping("/show")
	public ResponseEntity showImg(String path) {
		try {
			return ResponseEntity.ok(resourceLoader.getResource("file:" + String.valueOf(bladeProperties.getProp().get("remote-path")) + "/" + path));
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseEntity.notFound().build();
		}
	}

	private R commonUpload(MultipartFile file) {
		if (null == file) {
			return R.fail("请选择要上传的图片");
		}
		String originalFileName = file.getOriginalFilename();
		BladeFile bf = this.getFile(file);
		bf.transfer();
		Map param = new HashMap();
		param.put("url", bladeProperties.getProp().get("upload-domain") + "/images" + bf.getUploadVirtualPath().replace("//", "/"));
		param.put("name", originalFileName);
		return R.data(param);
	}


}
